<template>
  <view class="index-page">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input" @click="handleSearch">
        <view class="icon icon-search" style="font-size: 18px; color: #999">🔍</view>
        <text class="search-placeholder">搜索壁纸</text>
      </view>
    </view>
    
    <!-- Banner轮播图 -->
    <view class="banner-section">
      <swiper class="banner-swiper" autoplay indicator-dots circular
      duration="500"
      interval="3000" 
        @change="onBannerChange"
      >
        <swiper-item v-for="(banner, index) in banners" :key="index">
          <view class="banner-item" @click="handleBannerClick(banner)">
            <image :src="banner.imageUrl" mode="aspectFill" class="banner-image" />
            <view v-if="banner.title || banner.description" class="banner-overlay">
              <text v-if="banner.title" class="banner-title">{{ banner.title }}</text>
              <text v-if="banner.description" class="banner-desc">{{ banner.description }}</text>
            </view>
          </view>
        </swiper-item>
      </swiper>
      <!-- 自定义指示器 -->
      <view class="custom-indicator" v-if="banners.length > 1">
        <view 
          v-for="(banner, index) in banners" 
          :key="index"
          class="indicator-dot"
          :class="{ active: currentBannerIndex === index }"
        ></view>
      </view>
    </view>
    
    <!-- 分类导航 -->
    <view class="category-section">
      <view class="section-title">
        <text>分类</text>
        <view class="more" @click="navigateToCategory">
          <text>更多</text>
          <view class="icon icon-right" style="font-size: 14px; color: #999">›</view>
        </view>
      </view>
      <view class="category-grid">
        <view 
          v-for="category in categories.slice(0,8)" 
          :key="category._id"
          class="category-item"
          @click="navigateToCategoryList(category)"
        >
          <view class="category-icon">
            <view 
              class="category-icon-emoji" 
              :style="{ color: category.color || '#007aff', fontSize: '32px' }" 
            >
				{{category.icon}}
            </view>
          </view>
          <text class="category-name">{{ category.name }}</text>
        </view>
      </view>
    </view>
    
    <!-- 热门推荐 -->
    <view class="featured-section" v-if="featuredWallpapers.length > 0">
      <view class="section-title">
        <text>热门推荐</text>
      </view>
      <scroll-view 
        class="featured-scroll" 
        scroll-x 
        show-scrollbar="false"
        :scroll-into-view="featuredScrollIntoView"
      >
        <view 
          v-for="(item, index) in featuredWallpapers" 
          :key="item._id"
          :id="`featured-${index}`"
          class="featured-item"
          @click="navigateToDetail(item)"
        >
          <image 
            :src="item.thumbnail_url || item.file_url" 
            mode="aspectFill" 
            class="featured-image"
          />
          <text class="featured-title">{{ item.title }}</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 最新壁纸 -->
    <view class="latest-section">
      <view class="section-title">
        <text>最新壁纸</text>
      </view>
      <!-- 瀑布流壁纸列表 -->
      <wallpaper-grid 
        :wallpaper-list="wallpapers" 
        :has-more="hasMore" 
        :load-status="loadStatus"
        @wallpaper-click="navigateToDetail"
        @load-more="loadMoreWallpapers"
        @favorite="handleFavorite"
      />
    </view>
	<!-- 加载状态 -->
	<view v-if="isLoading" class="loading-state">
	  <uni-load-more :status="'loading'" />  
	</view>
  </view>
</template>

<script setup>
import { ref} from 'vue';
import  { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app"
import WallpaperGrid from '../../components/wallpaper-grid.vue';

// 状态管理
const wallpapers = ref([]);
const currentBannerIndex = ref(0);
const categories = ref([
  { _id: 'nature', name: '自然', icon: ' ', color: '#52c41a' },
  { _id: 'anime', name: '动漫', icon: ' ', color: '#faad14' },
  { _id: 'art', name: '艺术', icon: ' ', color: '#f5222d' },
  { _id: 'text', name: '文字', icon: ' ', color: '#1890ff' },
  { _id: 'car', name: '汽车', icon: ' ', color: '#722ed1' },
  { _id: 'landscape', name: '风景', icon: ' ', color: '#13c2c2' },
  { _id: 'abstract', name: '抽象', icon: ' ', color: '#eb2f96' },
  { _id: 'other', name: '其他', icon: ' ', color: '#8c8c8c' }
]);
const banners = ref([
  { 
    imageUrl: "https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/4a6024a0-6240-4b56-b071-7b0dfe8280e0.jpg",
    title: "自然风光壁纸",
    description: "精选高质量自然风景壁纸",
    linkType: "category",
    linkId: "nature"
  },
  { 
    imageUrl: "https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/7f61efc1-b049-4a3d-86c8-6cac0f2af0a5.jpg",
    title: "动漫壁纸特辑",
    description: "热门动漫角色壁纸",
    linkType: "category",
    linkId: "anime"
  },
  { 
    imageUrl: "https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/fe37c678-26d6-45dd-8aee-4648ec49f1c9.jpg",
    title: "艺术壁纸合集",
    description: "独特艺术风格壁纸",
    linkType: "category",
    linkId: "art"
 }
]);
const featuredWallpapers = ref([]);
const page = ref(1);
const size = ref(20);
const hasMore = ref(true);
const isLoading = ref(false);
const loadStatus = ref('more');
const featuredScrollIntoView = ref('');

// 模拟数据（实际应从云函数获取）
const mockWallpapers = [
  {
    _id: '1',
    title: '山川河流',
    thumbnail_url: "https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/4a6024a0-6240-4b56-b071-7b0dfe8280e0.jpg",
    file_url: "https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/fe37c678-26d6-45dd-8aee-4648ec49f1c9.jpg"
,
    favorite_count: 128,
    download_count: 512,
    is_favorite: false
  },
  {
    _id: '2',
    title: '动漫角色',
    thumbnail_url: "https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/7f61efc1-b049-4a3d-86c8-6cac0f2af0a5.jpg"
,
    file_url: "https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/7f61efc1-b049-4a3d-86c8-6cac0f2af0a5.jpg"
,
    favorite_count: 96,
    download_count: 384,
    is_favorite: true
  },
  {
    _id: '3',
    title: '艺术抽象',
    thumbnail_url: "https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/fe37c678-26d6-45dd-8aee-4648ec49f1c9.jpg"
,
    file_url: "https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/fe37c678-26d6-45dd-8aee-4648ec49f1c9.jpg"
,
    favorite_count: 64,
    download_count: 256,
    is_favorite: false
  },
  {
    _id: '4',
    title: '城市夜景',
    thumbnail_url: "https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/b9d2d8e5-1053-47e6-9e45-89a9d1990685.jpg",
    file_url:"https://mp-0a89a5fb-4655-475d-b507-d20401f9761d.cdn.bspapp.com/cloudstorage/b9d2d8e5-1053-47e6-9e45-89a9d1990685.jpg",
    favorite_count: 48,
    download_count: 192,
    is_favorite: false
  }
];

// 初始化加载
onLoad(() => {
  initData();
});

onShow(() => {
  // 页面显示时刷新数据
  if (page.value > 1) {
    page.value = 1;
    wallpapers.value = [];
    initData();
  }
});

// 触底加载更多
onReachBottom(() => {
  loadMoreWallpapers();
});
// 加载分类数据 管理员页面的分类数据建议后期修改
const getCategories = async () => {
  isLoading.value = true;
  
  try {
    // const res = await uniCloud.callFunction({
    //   name: 'admingetCategories'
    // });
    // if (res && res.result && res.result.code === 0) {
    //   categories.value = res.result.data || [];
    // }
    const categoriesRes = await uniCloud.callFunction({ name: 'categorygetList' });
    if (categoriesRes.result.code === 0) {
      categories.value = categoriesRes.result.data;
    }
  } catch (error) {
    console.error('加载分类失败:', error);
    // 使用模拟数据
    // mockCategories();
  } finally {
    isLoading.value = false;
  }
};
// 获取轮播图数据
const getBanners = async () => {
  try {
    // 这里可以替换为实际的云函数调用
    const res = await uniCloud.callFunction({ name: 'getBanners' });
    return res;
	console.log('获取轮播图',res);
    return { result: { data: banners.value } };
  } catch (error) {
    console.error('获取轮播图失败:', error);
    return { result: { data: banners.value } }; // 失败时返回默认数据
  }
};

// 初始化数据
const initData = async () => {
  try {
    // 获取分类（模拟数据）
    
    await getCategories();
    // 获取壁纸列表
    await getWallpapers();
    
    // 获取热门推荐
    await getFeaturedWallpapers();
    
    // 获取轮播图数据
    const bannersRes = await getBanners();
    if (bannersRes && bannersRes.result) {
      banners.value = bannersRes.result.data || banners.value;
    }
  } catch (error) {
    console.error('初始化数据失败:', error);
    uni.showToast({ title: '加载失败', icon: 'none' });
  }
};

// 获取壁纸列表
const getWallpapers = async () => {
  try {
    uni.showLoading({ title: '加载中' });
    
    // 尝试调用云函数获取数据
    try {
      const res = await uniCloud.callFunction({
        name: 'getList',
        data: {
          page: page.value,
          size: size.value
        }
      });
       console.log('获取最新----壁纸列表',res);
      // 如果云函数调用成功且有数据
      if (res.success) {
        if (res.result.data.page.value === 1) {
          wallpapers.value = res.result.data.list;
        } else {
          wallpapers.value = [...wallpapers.value, ...res.result.data.list];
        }
        hasMore.value = res.result.hasMore || false;
        
        // 如果是第一页加载，也初始化热门推荐
        if (res.result.data.page.value === 1) {
          featuredWallpapers.value = res.result.data.list.slice(0, 3);
        }
      } else {
        // 使用模拟数据
        console.log('云函数调用失败或无数据，使用模拟数据');
      }
    } catch (cloudError) {
      // 云函数调用失败，使用模拟数据
      console.log('云函数调用失败1，使用模拟数据:', cloudError);
      useMockData();
    }
    
    loadStatus.value = 'more';
  } catch (error) {
    console.error('获取壁纸失败:', error);
    loadStatus.value = 'error';
    uni.showToast({ title: '加载失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// 使用模拟数据
const useMockData = async () => {
  await new Promise(resolve => setTimeout(resolve, 500)); // 模拟网络延迟
  
  if (page.value === 1) {
    wallpapers.value = mockWallpapers;
  } else {
    // 模拟加载更多数据
    wallpapers.value = [...wallpapers.value, ...mockWallpapers.map((item, index) => ({
      ...item,
      _id: `${item._id}-page${page.value}-${index}`
    }))];
  }
  
  // 模拟没有更多数据的情况
  if (page.value >= 3) {
    hasMore.value = false;
  }
  
  // 如果是第一页加载，也初始化热门推荐
  if (page.value === 1) {
    featuredWallpapers.value = mockWallpapers.slice(0, 3);
  }
};

// 获取热门推荐
const getFeaturedWallpapers = async () => {
  try {
    const res = await uniCloud.callFunction({
      name: 'getFeatured',
      data: { limit: 6 }
    });
    
    console.log('获取热门推荐:', res);
    if (res.result && res.result.code === 200) {
      featuredWallpapers.value = res.result.data || [];
    } else {
      console.log('获取热门推荐失败:', res.result?.message);
      // 失败时使用模拟数据
      featuredWallpapers.value = mockWallpapers.slice(0, 3);
    }
  } catch (error) {
    console.log('获取热门推荐失败:', error);
    // 失败时使用模拟数据
    featuredWallpapers.value = mockWallpapers.slice(0, 3);
  }
};

// 加载更多壁纸
const loadMoreWallpapers = async () => {
  if (!hasMore.value || loadStatus.value === 'loading') return;
  
  loadStatus.value = 'loading';
  page.value++;
  await getWallpapers();
};

// 搜索处理
const handleSearch = () => {
  uni.navigateTo({ url: '/pages/search/search' });
};

// 导航到分类页面
const navigateToCategory = () => {
  // 跳转到分类列表页面
  uni.navigateTo({
    url: `/pages/category-list/category-list`
  });
};

// 轮播图相关方法
const onBannerChange = (e) => {
  currentBannerIndex.value = e.detail.current;
}

const handleBannerClick = (banner) => {
  // 根据banner的linkType进行不同的跳转
  if (banner.linkType === 'category' && banner.linkId) {
    navigateToCategory(banner.linkId);
  } else if (banner.linkType === 'detail' && banner.linkId) {
    navigateToDetail(banner.linkId);
  } else if (banner.linkType === 'page' && banner.linkUrl) {
    uni.navigateTo({
      url: banner.linkUrl
    });
  }
};

// 导航到分类列表
const navigateToCategoryList = (category) => {
  // 跳转到分类列表页面
  uni.navigateTo({
    url: `/pages/category-list/category-list?categoryId=${category._id}&categoryName=${encodeURIComponent(category.name)}`
  });
};

// 导航到详情页
const navigateToDetail = (item) => {
	console.log({item});
  uni.navigateTo({ url: `/pages/detail/detail?id=${item._id}` });
};

// 处理收藏
const handleFavorite = (updatedWallpaper) => {
  try {
    // 更新壁纸列表中的收藏状态
    const index = wallpapers.value.findIndex(item => item._id === updatedWallpaper._id);
    if (index !== -1) {
      wallpapers.value[index].is_favorite = updatedWallpaper.is_favorite;
      wallpapers.value[index].favorite_count = updatedWallpaper.favorite_count;
    }
    
    // 同时更新热门推荐中的对应项
    const featuredIndex = featuredWallpapers.value.findIndex(item => item._id === updatedWallpaper._id);
    if (featuredIndex !== -1) {
      featuredWallpapers.value[featuredIndex].is_favorite = updatedWallpaper.is_favorite;
      featuredWallpapers.value[featuredIndex].favorite_count = updatedWallpaper.favorite_count;
    }
  } catch (error) {
    console.error('更新收藏状态失败:', error);
  }
};
</script>

<style lang="less" scoped>
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.category-icon-emoji {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.index-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .search-bar {
    padding: 10px 16px;
    background-color: #fff;
    .search-input {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 12px;
      background-color: #f0f0f0;
      border-radius: 20px;
      .search-placeholder {
        color: #999;
        font-size: 14px;
      }
    }
  }
  
  .banner-section {
    width: 100%;
    height: 300rpx;
    margin-bottom: 16px;
    position: relative;
    .custom-indicator {
      position: absolute;
      bottom: 16rpx;
      right: 20rpx;
      display: flex;
      gap: 10rpx;
      z-index: 10;
    }

    .indicator-dot {
      width: 12rpx;
      height: 12rpx;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.5);
      transition: all 0.3s ease;
    }

    .indicator-dot.active {
      width: 30rpx;
      border-radius: 6rpx;
      background: #fff;
    }
    .banner-swiper {
      width: 100%;
      height: 100%;
      .banner-item {
        width: 100%;
        height: 100%;
        position: relative;
        overflow: hidden;
      }
      .banner-image {
        width: 100%;
        height: 100%;
        transition: transform 0.5s ease;
      }
      .banner-item:active .banner-image {
        transform: scale(1.05);
      }
      .banner-overlay {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 20rpx;
        background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
      }
      .banner-title {
        color: #fff;
        font-size: 32rpx;
        font-weight: bold;
        display: block;
        margin-bottom: 8rpx;
        text-shadow: 0 1rpx 2rpx rgba(0,0,0,0.8);
      }
      .banner-desc {
        color: #fff;
        font-size: 24rpx;
        opacity: 0.9;
        text-shadow: 0 1rpx 2rpx rgba(0,0,0,0.8);
      }
    }
  }
  
  .category-section {
    background-color: #fff;
    padding: 16px;
    margin-bottom: 16px;
    .section-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      text {
        font-size: 18px;
        font-weight: bold;
      }
      .more {
        display: flex;
        align-items: center;
        gap: 4px;
        text {
          color: #999;
          font-size: 14px;
        }
      }
    }
    .category-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 16px;
      .category-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
        .category-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          background-color: #f5f5f5;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .category-name {
          font-size: 14px;
          color: #333;
        }
      }
    }
  }
  
  .featured-section {
    background-color: #fff;
    padding: 16px;
    margin-bottom: 16px;
    .section-title {
      margin-bottom: 16px;
      text {
        font-size: 18px;
        font-weight: bold;
      }
    }
    .featured-scroll {
      white-space: nowrap;
      padding-bottom: 8px;
      .featured-item {
        display: inline-block;
        width: 140px;
        margin-right: 12px;
        .featured-image {
          width: 100%;
          height: 200px;
          border-radius: 8px;
          margin-bottom: 8px;
        }
        .featured-title {
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          font-size: 14px;
          color: #333;
          line-height: 1.4;
        }
      }
    }
  }
  
  .latest-section {
    background-color: #fff;
    padding: 16px 0;
    .section-title {
      padding: 0 16px 16px;
      text {
        font-size: 18px;
        font-weight: bold;
      }
    }
  }
}
</style>